<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800 mb-2">
        课程调整申请
      </h2>
      <p class="text-gray-500">请填写以下信息提交课程调整申请</p>
    </div>

    <!-- 原课程信息 -->
    <el-row class="mb-6">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="form-section">
            <h4 class="section-title">原课程信息</h4>
            <!-- 第一行：4列布局 -->
            <el-row :gutter="20" class="mb-2">
              <el-col :span="6">
                <el-form-item label="课程名称">
                  <el-input
                      :value="selectedCourseData.courseScheduleDetails?.className"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="班级名称">
                  <el-input
                      :value="selectedCourseData.courseScheduleDetails?.className"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="学年学期">
                  <el-input
                      :value="`${selectedCourseData.courseScheduleDetails?.academicYear || '2025'}-${selectedCourseData.courseScheduleDetails?.semester || '1'}学期`"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="班级容量">
                  <el-input
                      :value="`${selectedCourseData.courseScheduleDetails?.currentEnrollment}/${selectedCourseData.courseScheduleDetails?.maxCapacity}`"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行：4列布局 -->
            <el-row :gutter="20" class="mb-2">
              <el-col :span="6">
                <el-form-item label="上课时间">
                  <el-input
                      :value="getOriginalTimeText()"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="上课教室">
                  <el-input
                      :value="classroomName"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="上课周次">
                  <el-input
                      :value="`第${selectedCourseData.courseScheduleDetails?.startWeek}-${selectedCourseData.courseScheduleDetails?.endWeek}周`"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单双周">
                  <el-input
                      :value="selectedCourseData.courseScheduleDetails?.weekType === 2 ? '单周' : selectedCourseData.courseScheduleDetails?.weekType === 4 ? '双周' : '每周'"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行：4列布局 -->
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="授课教师">
                  <el-input
                      :value="getTeacherDisplayText()"
                      disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请日期">
                  <el-date-picker
                      v-model="adjustFormData.applyDate"
                      type="date"
                      placeholder="选择申请日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区：调整设置区域和课表区域各占一半 -->
    <el-row :gutter="20">
      <!-- 左侧：调整设置区域 -->
      <el-col :span="12">
        <el-card shadow="hover" class="h-full">
          <el-form
              ref="adjustFormRef"
              :model="adjustFormData"
              :rules="adjustFormRules"
              label-width="120px"
              class="adjust-form"
          >
            <!-- 调整范围 -->
            <div class="form-section">
              <h4 class="section-title">调整范围</h4>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="调整范围" prop="adjustmentRange">
                    <el-select
                        v-model="adjustFormData.adjustmentRange"
                        placeholder="请选择调整范围"
                        style="width: 100%"
                        @change="handleAdjustmentRangeChange"
                    >
                      <el-option :value="1" label="临时调整"></el-option>
                      <el-option :value="2" label="调整整个周期"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="调整原因" prop="adjustmentReason">
                <el-select
                    v-model="adjustFormData.adjustmentReason"
                    placeholder="请选择调整原因"
                    style="width: 100%"
                    clearable
                >
                  <el-option
                      v-for="dict in reasons_adjusting_course"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="详细说明" prop="adjustmentDescription">
                <el-input
                    v-model="adjustFormData.adjustmentDescription"
                    type="textarea"
                    :rows="3"
                    placeholder="请详细说明调整原因和具体情况（至少10个字符）"
                    maxlength="500"
                    show-word-limit
                ></el-input>
              </el-form-item>

              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                    v-model="adjustFormData.contactPhone"
                    placeholder="请输入联系电话"
                    maxlength="11"
                    style="width: 300px"
                ></el-input>
              </el-form-item>
            </div>

            <!-- 时间调整设置 -->
            <div class="form-section">
              <h4 class="section-title">时间调整设置</h4>

              <!-- 调整教学周（支持多选） -->
              <el-row :gutter="20" class="mb-2" v-if="adjustFormData.adjustmentRange === 1">
                <el-col :span="24">
                  <el-form-item label="调整教学周" prop="tempAdjustWeeks">
                    <el-select
                        v-model="adjustFormData.tempAdjustWeeks"
                        placeholder="选择需要调整的教学周（可多选）"
                        style="width: 100%"
                        multiple
                        @change="loadScheduleData"
                    >
                      <!-- 动态生成1-20周选项 -->
                      <el-option
                          v-for="week in 20"
                          :key="week"
                          :label="`第${week}周`"
                          :value="week"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 新教室（下拉选择框） -->
              <el-row :gutter="20" class="mb-2">
                <el-col :span="12">
                  <el-form-item label="新教室" prop="newClassroomId">
                    <el-select
                        v-model="adjustFormData.newClassroomId"
                        placeholder="请选择新的上课教室"
                        style="width: 100%"
                        @change="handleClassroomChange"
                        popper-max-height="400px"
                        filterable
                    >
                      <!-- 添加"不调整教室"选项 -->
                      <el-option
                          value=""
                          label="不调整教室"
                      />
                      <el-option
                          v-for="classroom in classrooms"
                          :key="classroom.id"
                          :label="classroom.classRoomName"
                          :value="classroom.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 时间设置 -->
              <el-row :gutter="20" class="mb-2">
                <el-col :span="10">
                  <el-form-item label="新上课星期" prop="newWeekDay">
                    <el-select
                        v-model="adjustFormData.newWeekDay"
                        placeholder="选择星期"
                        style="width: 100%"
                        @change="loadScheduleData"
                    >
                      <el-option
                          v-for="option in weekDayOptions"
                          :key="option.value"
                          :label="option.label"
                          :value="option.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="15">
                  <el-form-item label="开始时间" prop="newStartTime">
                    <el-select
                        v-model="adjustFormData.newStartTime"
                        placeholder="开始时间"
                        style="width: 100%"
                    >
                      <el-option
                          v-for="time in timeOptions"
                          :key="time"
                          :label="time"
                          :value="time"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="15">
                  <el-form-item label="结束时间" prop="newEndTime">
                    <el-select
                        v-model="adjustFormData.newEndTime"
                        placeholder="结束时间"
                        style="width: 100%"
                        @change="validateEndTime"
                    >
                      <el-option
                          v-for="time in timeOptions"
                          :key="time"
                          :label="time"
                          :value="time"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="adjustFormData.adjustmentRange === 2">
                  <el-form-item label="单双周">
                    <el-select
                        v-model="adjustFormData.newWeekType"
                        style="width: 100%"
                        @change="loadScheduleData"
                    >
                      <el-option
                          v-for="option in weekTypeOptions"
                          :key="option.value"
                          :label="option.label"
                          :value="option.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 整个周期调整的周次设置 -->
              <div v-if="adjustFormData.adjustmentRange === 2">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="开始周次" prop="newStartWeek">
                      <el-input
                          v-model="adjustFormData.newStartWeek"
                          placeholder="如：1"
                          @blur="validateWeeks"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束周次" prop="newEndWeek">
                      <el-input
                          v-model="adjustFormData.newEndWeek"
                          placeholder="如：16"
                          @blur="validateWeeks"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>

            <!-- 补充说明 -->
            <div class="form-section">
              <h4 class="section-title">补充说明</h4>
              <el-form-item label="备注信息">
                <el-input
                    v-model="adjustFormData.remarks"
                    type="textarea"
                    :rows="2"
                    placeholder="其他需要说明的信息（选填）"
                    maxlength="300"
                    show-word-limit
                ></el-input>
              </el-form-item>
            </div>

            <!-- 提示信息 -->
            <el-alert
                title="提交须知"
                type="info"
                :closable="false"
                class="mb-4"
            >
              <template #default>
                <ul class="notice-list">
                  <li>请确保填写信息准确无误，提交后将发送给相关审核人员</li>
                  <li>紧急调课请提前电话联系教务处，确保及时处理</li>
                  <li>调课申请一般需要提前3个工作日提交</li>
                  <li>如需取消已提交的申请，请联系教务处</li>
                </ul>
              </template>
            </el-alert>

            <!-- 操作按钮 -->
            <div class="dialog-footer mt-6">
              <el-button @click="goBack">返回</el-button>
              <el-button
                  type="primary"
                  @click="submitAdjustApplication"
                  :loading="submitting"
              >
                {{ submitting ? '提交中...' : '提交申请' }}
              </el-button>
            </div>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：课表区域 -->
      <el-col :span="12">
        <div class="full-width-row schedule-container h-full">
          <el-card class="schedule-card h-full">
            <div slot="header" style="text-align: center;">
              <span>课表</span>
            </div>
            <div class="card-content">
              <!-- 课表实现 -->
              <div class="grid-timetable">
                <!-- 顶部星期标题 -->
                <div class="timetable-header">
                  <div class="header-cell empty-cell"></div>
                  <div class="header-cell">星期一</div>
                  <div class="header-cell">星期二</div>
                  <div class="header-cell">星期三</div>
                  <div class="header-cell">星期四</div>
                  <div class="header-cell">星期五</div>
                  <div class="header-cell">星期六</div>
                  <div class="header-cell">星期日</div>
                </div>

                <!-- 课表主体（网格布局） -->
                <div class="timetable-body">
                  <!-- 左侧节次列 -->
                  <div class="lesson-index-column">
                    <div v-for="i in 10" :key="i" class="lesson-index">
                      <div class="lesson-time">
                        {{ getTimeRange(i) }}
                      </div>
                      <div class="lesson-number">
                        第{{ i }}节
                      </div>
                    </div>
                  </div>

                  <!-- 网格内容区域 -->
                  <div class="timetable-grid">
                    <div class="grid-container">
                      <!-- 加载状态 -->
                      <div v-if="scheduleLoading" class="schedule-loading">
                        <el-icon :size="30" class="mr-2">
                          <Loading />
                        </el-icon>
                        <p class="mt-2">加载课表中...</p>
                      </div>

                      <!-- 无数据状态 -->
                      <div v-else-if="allCourses.length === 0" class="no-schedule">
                        <el-empty description="暂无排课数据"></el-empty>
                      </div>

                      <!-- 动态生成课程元素 -->
                      <div
                          v-else
                          v-for="(course, index) in allCourses"
                          :key="index"
                          class="course-item"
                          :style="getCourseStyle(course)"
                          :class="`course-type-${course.type}`"
                      >
                        <!-- 课程Tooltip详情 -->
                        <el-tooltip
                            effect="dark"
                            placement="top"
                            :enterable="true"
                            :content="getCourseTooltipContent(course)"
                        >
                          <div class="course-color-block"></div>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 课程类型说明 -->
              <div class="schedule-legend mt-4">
                <h5 class="legend-title">课程类型说明</h5>
                <div class="legend-items">
                  <div class="legend-item">
                    <span class="color-marker course-type-1"></span>
                    <span class="legend-text">当前调整的课程</span>
                  </div>
                  <div class="legend-item">
                    <span class="color-marker course-type-3"></span>
                    <span class="legend-text">教师的其他课程</span>
                  </div>
                  <div class="legend-item">
                    <span class="color-marker course-type-5"></span>
                    <span class="legend-text">本班学生的其他课程</span>
                  </div>
                  <div class="legend-item">
                    <span class="color-marker course-type-4"></span>
                    <span class="legend-text">教室本周的其他课程</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, getCurrentInstance, watch} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {ElMessage, ElMessageBox, ElTooltip} from 'element-plus';
import {getTeacher} from "@/api/teacher/teacher.js";
import {listClassroom, getClassroom} from "@/api/classroom/classroom.js";
import {
  getResourceTimetable,
  getStudentTimetable,
  getTeacherNamesByCourseScheduleDetailsId
} from "@/api/course/availability";
import {insertAdjustmentRecord} from "@/api/trainingManagement/CourseAdjustmentRecord.js"
import {Loading} from '@element-plus/icons-vue';

// 路由相关
const router = useRouter();
const route = useRoute();

// 获取当前组件实例和字典数据
const {proxy} = getCurrentInstance();
const {reasons_adjusting_course} = proxy.useDict("reasons_adjusting_course");
const studentTimetableData = ref([]);
// 教师姓名列表（用于回显）
const teacherNames = ref([]);
// 教室名称（用于回显）
const classroomName = ref('加载中...');
// 教室列表数据
const classrooms = ref([]);
// 提交状态
const submitting = ref(false);
// 课表数据加载状态
const scheduleLoading = ref(false);
// 整合后的课程数据（用于网格课表）
const allCourses = ref([]);

// 从路由参数获取选中的课程数据
const selectedCourseData = ref({});

// 课程调整表单数据
const adjustFormData = reactive({
  // 关联字段
  courseScheduleDetailsId: '',
  classScheduleDetailedId: '',

  // 原课程信息
  originalCourseId: '',
  originalClassName: '',
  originalTeacherId: '',
  originalClassroom: '',
  originalStartTime: '',
  originalEndTime: '',
  originalWeekDay: '',
  originalWeekType: '',
  originalStartWeek: '',
  originalEndWeek: '',

  // 调整范围 - 修改为 adjustmentRange，使用数字类型
  adjustmentRange: null, // 1: 临时调整, 2: 调整整个周期

  // 新课程安排信息
  newClassroomId: '', // 存储选中的教室ID
  newStartTime: '',
  newEndTime: '',
  newWeekDay: '',
  newWeekType: 1,
  newStartWeek: '',
  newEndWeek: '',

  // 临时调整的教学周（多选）
  tempAdjustWeeks: [],

  // 申请信息
  adjustmentReason: null,
  adjustmentDescription: '',
  applicantId: '',
  contactPhone: '',
  urgentLevel: 1,
  applyDate: new Date().toISOString().split('T')[0],
  remarks: ''
});

// 监听调整范围变化，重置相关字段
const handleAdjustmentRangeChange = () => {
  if (adjustFormData.adjustmentRange === 1) {
    // 临时调整：清空周次设置
    adjustFormData.newStartWeek = '';
    adjustFormData.newEndWeek = '';
  } else {
    // 调整整个周期：清空临时调整周次
    adjustFormData.tempAdjustWeeks = [];
  }
  loadScheduleData();
};

// 星期选项
const weekDayOptions = [
  {value: 1, label: '周一'},
  {value: 2, label: '周二'},
  {value: 3, label: '周三'},
  {value: 4, label: '周四'},
  {value: 5, label: '周五'},
  {value: 6, label: '周六'},
  {value: 7, label: '周日'}
];

// 单双周选项
const weekTypeOptions = [
  {value: 1, label: '每周'},
  {value: 2, label: '单周'},
  {value: 4, label: '双周'}
];

// 时间选项
const timeOptions = [
  '10:00', '10:45', '10:55', '11:40', '12:10', '12:55',
  '13:05', '13:50', '15:00', '15:45', '15:55', '16:40',
  '17:10', '17:55', '18:05', '18:50', '21:00', '21:45',
  '21:55', '22:40'
];

// 表单验证规则 - 修改为 adjustmentRange
const adjustFormRules = {
  adjustmentRange: [
    {required: true, message: '请选择调整范围', trigger: 'change'}
  ],
  adjustmentReason: [
    {required: true, message: '请选择调整原因', trigger: 'change'}
  ],
  adjustmentDescription: [
    {required: true, message: '请输入详细说明', trigger: 'blur'},
    {min: 10, message: '详细说明至少10个字符', trigger: 'blur'}
  ],
  contactPhone: [
    {required: true, message: '请输入联系电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  tempAdjustWeeks: [
    {
      required: (() => adjustFormData.adjustmentRange === 1),
      message: '请选择调整教学周',
      trigger: 'change'
    }
  ],
  newWeekDay: [
    {
      required: true,
      message: '请选择新的上课星期',
      trigger: 'change'
    }
  ],
  newStartTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: 'change'
    }
  ],
  newEndTime: [
    {
      required: true,
      message: '请选择结束时间',
      trigger: 'change'
    }
  ],
  newClassroomId: [
    {
      required: false,  // 允许为空，支持"不调整教室"
      message: '请选择新的上课教室',
      trigger: 'change'
    }
  ],
  newStartWeek: [
    {
      required: (() => adjustFormData.adjustmentRange === 2),
      validator: (rule, value, callback) => {
        if (!value) callback(new Error('请输入开始周次'));
        else if (!/^\d+$/.test(value)) callback(new Error('请输入有效的周次数字'));
        else callback();
      },
      trigger: 'blur'
    }
  ],
  newEndWeek: [
    {
      required: (() => adjustFormData.adjustmentRange === 2),
      validator: (rule, value, callback) => {
        if (!value) callback(new Error('请输入结束周次'));
        else if (!/^\d+$/.test(value)) callback(new Error('请输入有效的周次数字'));
        else callback();
      },
      trigger: 'blur'
    }
  ]
};

const adjustFormRef = ref();

// 根据教室ID获取教室名称
const fetchClassroomName = async (classroomId) => {
  console.log('开始获取教室信息，教室ID:', classroomId);

  if (!classroomId) {
    console.warn('教室ID为空，无法获取教室信息');
    classroomName.value = '未知教室';
    return;
  }

  try {
    const response = await getClassroom(classroomId);
    console.log('获取教室信息响应:', response);

    if (response && response.code === 200 && response.data) {
      const classroom = response.data;
      console.log('教室数据:', classroom);

      if (classroom.classRoomName) {
        classroomName.value = classroom.classRoomName;
      } else if (classroom.buildingId && classroom.roomNumber) {
        classroomName.value = `${classroom.buildingId}-${classroom.roomNumber}`;
      } else if (classroom.buildingId) {
        classroomName.value = classroom.buildingId;
      } else {
        classroomName.value = '未知教室';
      }

      console.log('成功获取教室名称:', classroomName.value);
    } else {
      console.warn('获取教室信息失败，返回数据格式异常');
      classroomName.value = '未知教室';
    }
  } catch (error) {
    console.error('获取教室信息异常:', error);
    classroomName.value = '未知教室';
    ElMessage.error('获取教室信息失败');
  }
};

// 获取教师姓名显示文本
const getTeacherDisplayText = () => {
  if (teacherNames.value.length === 0) {
    return '加载中...';
  }
  return teacherNames.value.join('、');
};

// 根据课程班ID获取教师姓名列表
const fetchTeacherNames = async (courseScheduleDetailsId) => {
  console.log('开始获取教师姓名列表，课程班ID:', courseScheduleDetailsId);

  if (!courseScheduleDetailsId) {
    console.warn('课程班ID为空，无法获取教师姓名');
    teacherNames.value = ['未知教师'];
    return;
  }

  try {
    const response = await getTeacherNamesByCourseScheduleDetailsId(courseScheduleDetailsId);
    console.log('获取教师姓名列表响应:', response);

    if (response && Array.isArray(response)) {
      teacherNames.value = response;
      console.log('成功获取教师姓名列表:', teacherNames.value);
    } else {
      console.warn('获取教师姓名列表失败，返回数据格式异常');
      teacherNames.value = ['未知教师'];
    }
  } catch (error) {
    console.error('获取教师姓名列表异常:', error);
    teacherNames.value = ['未知教师'];
    ElMessage.error('获取教师信息失败');
  }
};

// 转换学生课表数据为课表格式
const transformStudentTimetable = (weekdays) => {
  studentTimetableData.value = [];
  weekdays.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    weekday.timeSlots.forEach(slot => {
      slot.courses.forEach(course => {
        const start = parseInt(course.startLesson);
        const end = parseInt(course.endLesson);
        if (!isNaN(start) && !isNaN(end) && start >= 1 && end <= 10) {
          studentTimetableData.value.push({
            xq: xq,
            start: start,
            end: end,
            title: course.title || "学生其他课程",
            addr: course.location || "",
            skjc: `${start}-${end}节`,
            jxbzc: course.extraInfo?.weekType || '',
            num: slot.timePeriod || '未知时段',
            type: 5
          });
        }
      });
    });
  });
};

// 获取当前课程班学生的其他课表
const fetchStudentTimetable = async () => {
  const courseScheduleDetailsId = selectedCourseData.value?.courseScheduleDetails?.id;
  if (!courseScheduleDetailsId) {
    console.warn("未获取到课程详情ID，无法加载学生课表");
    return;
  }

  try {
    const response = await getStudentTimetable(courseScheduleDetailsId);
    if (response.code === 200) {
      const studentData = response.params?.data;
      if (studentData?.weekdays && Array.isArray(studentData.weekdays)) {
        transformStudentTimetable(studentData.weekdays);
      }
    }
  } catch (error) {
    console.error("获取学生课表失败:", error);
  }
};

// 获取教室列表数据
const getClassroomList = async () => {
  try {
    let pageNum = 1;
    const pageSize = 100;
    let allClassrooms = [];
    let hasMore = true;

    while (hasMore) {
      const response = await listClassroom({pageNum, pageSize});
      if (response && response.code === 200 && Array.isArray(response.rows)) {
        allClassrooms = [...allClassrooms, ...response.rows];
        const total = response.total || 0;
        hasMore = pageNum * pageSize < total;
        pageNum++;
      } else {
        hasMore = false;
      }
    }

    classrooms.value = allClassrooms;
    console.log('教室列表加载完成，共', classrooms.value.length, '个教室');
  } catch (error) {
    ElMessage.error('获取教室列表时发生错误');
    console.error('教室列表接口异常:', error);
  }
};

// 处理教室选择变化
const handleClassroomChange = (classroomId) => {
  loadScheduleData();
};

// 加载课表数据
const loadScheduleData = async () => {
  allCourses.value = [];
  scheduleLoading.value = true;

  try {
    const allScheduleData = [];
    const courseDetails = selectedCourseData.value?.courseScheduleDetails;
    const academicYear = courseDetails?.academicYear ?? 0;
    const originalTeacherId = courseDetails?.teacherId;
    const originalClassroomId = courseDetails?.classroom || '';

    const selectedClassroomId = adjustFormData.newClassroomId === ''
        ? originalClassroomId
        : adjustFormData.newClassroomId;

    if (originalTeacherId) {
      const teacherData = await fetchResourceSchedule(originalTeacherId, academicYear, 3);
      allScheduleData.push(...teacherData);
    }

    if (selectedClassroomId) {
      const classroomData = await fetchResourceSchedule(selectedClassroomId, academicYear, 4);
      allScheduleData.push(...classroomData);
    }

    await fetchStudentTimetable();

    const transformedResourceData = transformToGridFormat(allScheduleData);
    const mergedData = [...transformedResourceData, ...studentTimetableData.value];

    const dataWithOverlap = processCoursesWithOverlap(mergedData);
    const conflictHandledData = handleConflictingCourses(dataWithOverlap);

    conflictHandledData.sort((a, b) => {
      if (a.xq !== b.xq) return a.xq - b.xq;
      if (a.start !== b.start) return a.start - b.start;
      return a.overlapIndex - b.overlapIndex;
    });

    allCourses.value = conflictHandledData;

  } catch (error) {
    ElMessage.error('获取课表数据失败，请稍后重试');
    console.error('课表加载异常:', error);
  } finally {
    scheduleLoading.value = false;
  }
};

// 找出每个时间段的所有重叠课程
const getOverlappingGroups = (courses) => {
  const timeSlotMap = {};

  courses.forEach(course => {
    const key = `${course.xq}-${course.start}-${course.end}`;
    if (!timeSlotMap[key]) {
      timeSlotMap[key] = [];
    }
    timeSlotMap[key].push(course);
  });

  return timeSlotMap;
};

// 处理课程数据，添加重叠信息
const processCoursesWithOverlap = (courses) => {
  const timeSlotMap = getOverlappingGroups(courses);

  return courses.map(course => {
    const key = `${course.xq}-${course.start}-${course.end}`;
    const group = timeSlotMap[key];
    const total = group.length;
    const index = group.findIndex(item => item === course);

    return {
      ...course,
      overlapTotal: total,
      overlapIndex: index
    };
  });
};

// 获取资源课表的通用方法
const fetchResourceSchedule = async (resourceId, academicYear, type) => {
  if (!resourceId) {
    console.warn('resourceId缺失');
    return [];
  }
  try {
    const response = await getResourceTimetable(resourceId, academicYear);
    if (response.code === 200) {
      const weekdays = response.data?.weekdays || response.params?.data?.weekdays;
      if (Array.isArray(weekdays)) {
        return weekdays.map(weekday => ({...weekday, type}));
      }
    }
    console.warn('接口返回格式异常:', response);
    return [];
  } catch (error) {
    console.error('接口调用失败:', error);
    return [];
  }
};

// 转换教师/教室数据格式
const transformToGridFormat = (rawData) => {
  const transformed = [];
  const currentCourseId = selectedCourseData.value?.courseScheduleDetails?.id;

  rawData.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    if (!weekday.timeSlots || !Array.isArray(weekday.timeSlots)) return;

    weekday.timeSlots.forEach(slot => {
      if (!slot.courses || !Array.isArray(slot.courses)) return;

      slot.courses.forEach(course => {
        const isCurrentCourse = course.id === currentCourseId;
        const start = Number(course.startLesson);
        const end = Number(course.endLesson);

        if (isNaN(start) || isNaN(end) || start < 1 || end > 10 || start > end) {
          return;
        }

        transformed.push({
          xq: xq,
          start: start,
          end: end,
          title: course.title || '未命名课程',
          skjc: `${start}-${end}节`,
          addr: course.location || '无地点',
          jxbzc: course.extraInfo?.isAvailable === 0 ? '已占用' : '可用',
          num: slot.timePeriod || '未知时段',
          type: isCurrentCourse ? 1 : (weekday.type || 3)
        });
      });
    });
  });
  return transformed;
};

// 网格课表专用方法：获取节次时间范围
const getTimeRange = (lessonNum) => {
  const timeRanges = [
    '10:00-10:45', '10:55-11:40', '12:10-12:55', '13:05-13:55',
    '15:00-15:45', '15:55-16:40', '17:10-17:55', '18:05-18:50',
    '20:00-20:45', '20:55-21:40'
  ];
  return timeRanges[lessonNum - 1] || '';
};

// 获取当前调整的课程（type:1）
const getCurrentAdjustCourse = (courses) => {
  return courses.find(course => course.type === 1) || null;
};

// 检查两个课程是否冲突
const isConflicting = (currentCourse, otherCourse) => {
  return currentCourse.start <= otherCourse.end && currentCourse.end >= otherCourse.start;
};

// 处理与当前课程冲突的课程
const handleConflictingCourses = (allCourses) => {
  const currentCourse = getCurrentAdjustCourse(allCourses);
  if (!currentCourse) return allCourses;

  const processedCourses = [];
  allCourses.forEach(course => {
    if (course.type === 1) {
      processedCourses.push(course);
      return;
    }

    if (!isConflicting(currentCourse, course)) {
      processedCourses.push(course);
      return;
    }

    const {start: currStart, end: currEnd} = currentCourse;
    const {start: otherStart, end: otherEnd} = course;

    if (otherStart >= currStart && otherEnd <= currEnd) {
      return;
    }

    if (otherStart < currStart && otherEnd <= currEnd && otherEnd >= currStart) {
      processedCourses.push({
        ...course,
        start: otherStart,
        end: currStart - 1
      });
      return;
    }

    if (otherStart >= currStart && otherStart <= currEnd && otherEnd > currEnd) {
      processedCourses.push({
        ...course,
        start: currEnd + 1,
        end: otherEnd
      });
      return;
    }

    if (otherStart < currStart && otherEnd > currEnd) {
      processedCourses.push({
        ...course,
        start: otherStart,
        end: currStart - 1
      });
      processedCourses.push({
        ...course,
        start: currEnd + 1,
        end: otherEnd
      });
      return;
    }
  });

  return processedCourses;
};

// 网格课表专用方法：计算课程样式（定位和宽度）
const getCourseStyle = (course) => {
  const colIndex = course.xq - 1;
  const rowIndex = course.start - 1;
  const rowSpan = course.end - course.start + 1;
  const zIndex = course.type === 1 ? 10 : 1;

  const totalOverlaps = course.overlapTotal || 1;
  const baseWidth = 100 / totalOverlaps;
  const startPercent = (course.overlapIndex || 0) * baseWidth;

  return {
    gridRow: `${rowIndex + 1} / span ${rowSpan}`,
    gridColumn: `${colIndex + 1}`,
    zIndex: zIndex,
    width: `${baseWidth}%`,
    left: `${startPercent}%`
  };
};

// 生成课程Tooltip内容
const getCourseTooltipContent = (course) => {
  return `
    <div style="text-align: left; padding: 5px;">
      <div><strong>${course.title}</strong></div>
      <div>节次：${course.skjc}</div>
      <div>地点：${course.addr}</div>
      <div>周次：${course.num}</div>
      <div>${course.jxbzc}</div>
    </div>
  `;
};

// 验证结束时间
const validateEndTime = () => {
  if (adjustFormData.newStartTime && adjustFormData.newEndTime && adjustFormData.newStartTime >= adjustFormData.newEndTime) {
    ElMessage.warning('结束时间必须晚于开始时间');
    adjustFormData.newEndTime = '';
  }
};

// 验证周次
const validateWeeks = () => {
  if (adjustFormData.newStartWeek && adjustFormData.newEndWeek) {
    const start = parseInt(adjustFormData.newStartWeek);
    const end = parseInt(adjustFormData.newEndWeek);
    if (start > end) {
      ElMessage.warning('结束周次必须大于等于开始周次');
      adjustFormData.newEndWeek = '';
    }
  }
};

// 根据教室ID获取教室名称（适配不调整场景）
const getClassroomName = (classroomId) => {
  if (!classroomId && classroomId !== 0) {
    return '不调整教室';
  }
  const selectedClassroom = classrooms.value.find(c => c.id === classroomId);
  return selectedClassroom ? (selectedClassroom.classRoomName || `${selectedClassroom.buildingId}-${selectedClassroom.roomNumber}`) : '未知教室';
};

// 获取调整范围文本
const getAdjustmentRangeText = (range) => {
  const rangeMap = {
    1: '临时调整',
    2: '调整整个周期'
  };
  return rangeMap[range] || '未知';
};

// 获取原时间文本
const getOriginalTimeText = () => {
  const schedule = selectedCourseData.value?.classScheduleDetailedList?.[0] || {};
  if (!schedule.weekDay) return '';
  return `${getWeekDay(schedule.weekDay)} ${schedule.startTime}-${schedule.endTime}（教室：${classroomName.value}）`;
};

// 转换星期几
const getWeekDay = (day) => {
  const weekdays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  return weekdays[day] || '未知';
};

// 提交调整申请
const submitAdjustApplication = async () => {
  if (!adjustFormRef.value) return;
  try {
    await adjustFormRef.value.validate();
    await confirmAdjustment();
    submitting.value = true;

    const courseDetails = selectedCourseData.value?.courseScheduleDetails || {};
    const originalSchedule = selectedCourseData.value?.classScheduleDetailedList?.[0] || {};

    const originalClassroomId = courseDetails.classroom || '';
    const originalClassroomName = classroomName.value || '未知教室';

    let finalClassroomId, finalClassroomName;
    if (adjustFormData.newClassroomId === '') {
      finalClassroomId = originalClassroomId;
      finalClassroomName = originalClassroomName;
    } else {
      const selectedClassroom = classrooms.value.find(c => c.id === adjustFormData.newClassroomId) || {};
      finalClassroomId = selectedClassroom.id || originalClassroomId;
      finalClassroomName = selectedClassroom.classRoomName || `${selectedClassroom.buildingId}-${selectedClassroom.roomNumber}` || originalClassroomName;
    }

    // 构建提交数据 - 完全按照后端字段结构
    const adjustmentRecord = {
      // 关联字段
      courseScheduleDetailsId: courseDetails.id,
      classScheduleDetailedId: originalSchedule.id,

      // 原始课程信息
      originalCourseId: courseDetails.courseId,
      originalClassName: courseDetails.className,
      originalTeacherId: courseDetails.teacherId || null,
      originalClassroom: originalClassroomName,
      originalStartTime: originalSchedule.startTime,
      originalEndTime: originalSchedule.endTime,
      originalWeekDay: originalSchedule.weekDay,
      originalWeekType: courseDetails.weekType || null,
      originalStartWeek: courseDetails.startWeek,
      originalEndWeek: courseDetails.endWeek,

      // 调整申请信息 - 使用 adjustmentRange
      adjustmentRange: adjustFormData.adjustmentRange,
      adjustmentReason: adjustFormData.adjustmentReason,
      adjustmentDescription: adjustFormData.adjustmentDescription,
      applicantId: adjustFormData.applicantId || '',
      contactPhone: adjustFormData.contactPhone,
      applyDate: adjustFormData.applyDate,
      remarks: adjustFormData.remarks,
      approvalStatus: '0',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),

      // 调整后信息
      newClassroom: finalClassroomName,
      newStartTime: adjustFormData.newStartTime || originalSchedule.startTime,
      newEndTime: adjustFormData.newEndTime || originalSchedule.endTime,
      newWeekDay: adjustFormData.newWeekDay || originalSchedule.weekDay,
      newWeekType: adjustFormData.newWeekType || courseDetails.weekType || 1,
      newStartWeek: adjustFormData.newStartWeek ? parseInt(adjustFormData.newStartWeek) : courseDetails.startWeek,
      newEndWeek: adjustFormData.newEndWeek ? parseInt(adjustFormData.newEndWeek) : courseDetails.endWeek,
      tempAdjustWeeks: adjustFormData.tempAdjustWeeks
    };

    console.log('准备提交的数据:', adjustmentRecord);

    // 构建需要更新的课程详情 - 关键修改：无论什么调整范围都构建课程详情
    let scheduleDetailsToUpdate = null;

    // 无论是临时调整还是整个周期调整，都需要构建课程详情
    if (adjustFormData.adjustmentRange === 1 || adjustFormData.adjustmentRange === 2) {
      scheduleDetailsToUpdate = {
        id: courseDetails.id,
        className: courseDetails.className,
        teacherId: courseDetails.teacherId,
        classroom: finalClassroomName,
        classroomId: finalClassroomId,
        startWeek: adjustFormData.newStartWeek ? parseInt(adjustFormData.newStartWeek) : courseDetails.startWeek,
        endWeek: adjustFormData.newEndWeek ? parseInt(adjustFormData.newEndWeek) : courseDetails.endWeek,
        weekType: adjustFormData.newWeekType || courseDetails.weekType || 1,
        classScheduleDetailedList: [
          {
            id: originalSchedule.id,
            weekDay: adjustFormData.newWeekDay || originalSchedule.weekDay,
            startTime: adjustFormData.newStartTime || originalSchedule.startTime,
            endTime: adjustFormData.newEndTime || originalSchedule.endTime,
            lessonCount: originalSchedule.lessonCount
          }
        ]
      };
    }

    console.log('课程详情数据:', scheduleDetailsToUpdate);

    // 提交数据
    const response = await insertAdjustmentRecord({
      adjustmentRecord: adjustmentRecord,
      scheduleDetails: scheduleDetailsToUpdate
    });

    console.log('处理后的响应:', response);

    if (response && (response.code === 200 || response.success === true)) {
      ElMessage.success('课程调整申请提交成功！');
      setTimeout(() => {
        router.back();
      }, 1500);
    } else {
      const errorMsg = response?.msg || response?.message || '提交失败，请稍后重试';
      throw new Error(errorMsg);
    }

  } catch (error) {
    console.error('提交失败详情:', error);
    ElMessage.error(error.message || '提交失败，请检查填写信息');
  } finally {
    submitting.value = false;
  }
};

// 提交前确认对话框
const confirmAdjustment = () => {
  return new Promise((resolve, reject) => {
    const currentClassroom = getClassroomName(adjustFormData.newClassroomId);
    ElMessageBox.confirm(
        `
      <div style="text-align: left;">
        <p>确认提交课程调整申请？</p>
        <p>调整范围：${getAdjustmentRangeText(adjustFormData.adjustmentRange)}</p>
        <p>新教室：${currentClassroom}</p>
        <p>新时间：${getWeekDay(adjustFormData.newWeekDay)} ${adjustFormData.newStartTime}-${adjustFormData.newEndTime}</p>
      </div>
      `,
        '确认提交',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
    ).then(() => resolve()).catch(() => reject());
  });
};

// 返回上一页
const goBack = () => {
  if (Object.values(adjustFormData).some(v => v !== '' && v != null)) {
    ElMessageBox.confirm(
        '确定要返回吗？已填写的信息将会丢失。',
        '确认返回',
        {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
    ).then(() => router.back());
  } else {
    router.back();
  }
};

// 页面初始化
onMounted(async () => {
  if (route.query.courseData) {
    try {
      const parsedData = JSON.parse(route.query.courseData);
      console.log('解析后的课程数据:', parsedData);
      selectedCourseData.value = Array.isArray(parsedData) ? parsedData[0] : parsedData;

      const courseDetails = selectedCourseData.value?.courseScheduleDetails || {};
      const schedule = selectedCourseData.value?.classScheduleDetailedList?.[0] || {};

      adjustFormData.originalCourseId = courseDetails.courseId;
      adjustFormData.originalClassName = courseDetails.className;
      adjustFormData.originalTeacherId = courseDetails.teacherId;
      adjustFormData.originalClassroom = courseDetails.classroom;
      adjustFormData.originalStartWeek = courseDetails.startWeek;
      adjustFormData.originalEndWeek = courseDetails.endWeek;
      adjustFormData.originalWeekType = courseDetails.weekType;
      adjustFormData.originalWeekDay = schedule.weekDay;
      adjustFormData.originalStartTime = schedule.startTime;
      adjustFormData.originalEndTime = schedule.endTime;

      await Promise.all([
        courseDetails.id ? fetchTeacherNames(courseDetails.id) : Promise.resolve(),
        courseDetails.classroom ? fetchClassroomName(courseDetails.classroom) : Promise.resolve(),
        getClassroomList(),
        selectedCourseData.value?.courseScheduleDetails ? fetchStudentTimetable() : Promise.resolve()
      ]);

      loadScheduleData();

    } catch (error) {
      console.error('课程数据解析失败:', error.message);
      ElMessage.error('课程数据格式错误，请返回重新选择');
    }
  } else {
    ElMessage.warning('未获取到课程信息');
  }
});

// 监听教室选择变化，自动加载课表
watch(
    () => adjustFormData.newClassroomId,
    (newVal) => {
      loadScheduleData();
    }
);
</script>

<style scoped lang="scss">
/* 样式保持不变 */
::v-deep .el-card__body {
  padding: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 16px;
}

.adjust-form {
  .form-section {
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 2px solid #E4E7ED;
    }
  }
}

.notice-list {
  margin: 0;
  padding-left: 16px;

  li {
    margin-bottom: 4px;
    color: #606266;
    font-size: 13px;
  }
}

.dialog-footer {
  text-align: right;

  .el-button {
    margin-left: 12px;
  }
}

.h-full {
  height: 100%;
  min-height: 100%;
}

.schedule-container {
  width: 100%;
  height: 100%;
}

.schedule-card {
  height: 100%;
  min-height: 800px;

  .card-content {
    padding: 10px;
    height: calc(100% - 56px);
    overflow-y: auto;
  }
}

.grid-timetable {
  width: 100%;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  background-color: #ffffff;
}

.timetable-header {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}

.header-cell {
  flex: 1;
  padding: 8px 0;
  text-align: center;
  font-weight: bold;
  border-right: 1px solid #e8e8e8;
  font-size: 12px;

  &:last-child {
    border-right: none;
  }
}

.empty-cell {
  flex: 0 0 80px;
  border-right: 1px solid #e8e8e8;
}

.timetable-body {
  display: flex;
}

.lesson-index-column {
  width: 80px;
  border-right: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}

.lesson-index {
  height: 60px;
  border-bottom: 1px solid #e8e8e8;
  padding: 5px;
  box-sizing: border-box;

  &:last-child {
    border-bottom: none;
  }
}

.lesson-time {
  font-size: 11px;
  color: #666;
  text-align: center;
}

.lesson-number {
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  margin-top: 3px;
}

.timetable-grid {
  flex: 1;
  overflow: hidden;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(10, 60px);
  grid-gap: 1px;
  background-color: #e8e8e8;
  height: 600px;
  position: relative;
}

.course-item {
  position: relative;
  height: 100%;
  padding: 0;
  border-radius: 3px;
  overflow: hidden;
  cursor: pointer;
  box-sizing: border-box;
  transition: all 0.2s;

  &:hover {
    transform: scale(1.02);
    z-index: 20 !important;
  }
}

.course-color-block {
  width: 100%;
  height: 100%;
  border-radius: 3px;
}

// 移除原有课程文字样式
.course-title, .course-detail {
  display: none;
}

.schedule-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.no-schedule {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 1200px) {
  ::v-deep .el-row {
    flex-direction: column;
  }

  ::v-deep .el-col {
    width: 100% !important;
    margin-bottom: 20px;
  }

  .schedule-card {
    min-height: 600px;
  }
}

.schedule-legend {
  padding: 10px 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.legend-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  padding-bottom: 5px;
  border-bottom: 1px dashed #e0e0e0;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.color-marker {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 3px;
  margin-right: 6px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

// 课程类型颜色
.course-type-1 {
  background-color: rgba(103, 194, 58, 0.85);
  border: 2px solid #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.course-type-3 {
  background-color: rgba(64, 158, 255, 0.85);
  color: white;
}

.course-type-4 {
  background-color: rgba(245, 108, 108, 0.85);
  color: white;
}

.course-type-5 {
  background-color: rgba(192, 99, 250, 0.85);
  color: white;
}

// Tooltip样式优化
::v-deep .el-tooltip__popper {
  max-width: 300px;
  padding: 8px 10px;
}
</style>